﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using DocumentFormat.OpenXml.Packaging;

namespace Note_CHUSHI
{
    public class Note
    {
        //标题
        public string Title { get; set; }
        //内容
        public string Content { get; set; }
        //创建时间
        public DateTime CreatedTime { get; set; }
        //修改时间
        public DateTime ModifiedTime { get; set; }
        public string FilePath { get; private set; }
        //新增用户名属性
        public string Username;
        public Note(string username)
        {
            CreatedTime = DateTime.Now;
            ModifiedTime = DateTime.Now;
            Username = username;
        }
        //设置文件路径
        public void SetFilePath(string path)
        {
            FilePath = path;
        }
        //保存笔记
        public void Save()
        {           
            if (string.IsNullOrEmpty(FilePath))
            {
                string safeTitle = MakeValidFileName(Title);
                // 修改为使用AccountService获取路径
                FilePath = Path.Combine(
                  //  AccountService.GetUserNotesDirectory(Path.GetFileName(Path.GetDirectoryName(FilePath))),
                  AccountService.GetUserNotesDirectory(Username),
                    $"{safeTitle}_{CreatedTime:yyyyMMddHHmmss}.rtf");
            }
            Directory.CreateDirectory(Path.GetDirectoryName(FilePath));
            Title = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(Title));
            Content = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(Content));

            if (Path.GetExtension(FilePath).ToLower() == ".txt")
            {
                File.WriteAllText(FilePath, Content, Encoding.UTF8);
            }
            else if (Path.GetExtension(FilePath).ToLower() == ".docx")
            {
                SaveAsWord(FilePath);
            }
            else if (Path.GetExtension(FilePath).ToLower() == ".pdf")
            {
                SaveAsPdf(FilePath);
            }
            else
            {
                File.WriteAllText(FilePath, Content); // 默认保存为 RTF
            }
            ModifiedTime = DateTime.Now;
        }
        //删除
        public void Delete()
        {
            if (File.Exists(FilePath))
            {
                File.Delete(FilePath);
            }
        }
        //从文件加载笔记
        public static Note LoadFromFile(string filePath)
        {
            string username = Path.GetFileName(Path.GetDirectoryName(filePath));
            //创建新的Note对象并设置属性
            var note = new Note(username)
            {
                FilePath = filePath,
                Content = File.ReadAllText(filePath),
                CreatedTime = File.GetCreationTime(filePath),
                ModifiedTime = File.GetLastWriteTime(filePath)
            };
            // 根据文件扩展名加载内容
            if (Path.GetExtension(filePath).ToLower() == ".txt")
            {
                note.Content = File.ReadAllText(filePath, Encoding.UTF8);
            }
            else if (Path.GetExtension(filePath).ToLower() == ".docx")
            {
                note.Content = LoadWordContent(filePath);
            }
            else if (Path.GetExtension(filePath).ToLower() == ".pdf")
            {
                note.Content = LoadPdfContent(filePath);
            }
            else
            {
                note.Content = File.ReadAllText(filePath); // 默认加载 RTF
            }
            //从文件中提取文件名
            string fileName = Path.GetFileNameWithoutExtension(filePath);
            int lastUnderscore = fileName.LastIndexOf('_');
            note.Title = lastUnderscore > 0 ? fileName.Substring(0, lastUnderscore) : fileName;

            return note;
        }

        //非法字符替换为下划线
        private string MakeValidFileName(string name)
        {
            foreach (char c in Path.GetInvalidFileNameChars())
            {
                name = name.Replace(c, '_');
            }
            return name;
        }
        private void SaveAsWord(string filePath)
        {
            try
            {
                using (var wordDocument = WordprocessingDocument.Create(filePath, DocumentFormat.OpenXml.WordprocessingDocumentType.Document))
                {
                    var mainPart = wordDocument.AddMainDocumentPart();
                    mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
                    var body = new DocumentFormat.OpenXml.Wordprocessing.Body();

                    // 添加标题
                    var titleParagraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(
                        new DocumentFormat.OpenXml.Wordprocessing.Run(
                            new DocumentFormat.OpenXml.Wordprocessing.Text(Title))
                    );
                    //标题居中
                    titleParagraph.ParagraphProperties = new DocumentFormat.OpenXml.Wordprocessing.ParagraphProperties
                    {
                        Justification = new DocumentFormat.OpenXml.Wordprocessing.Justification
                        {
                            Val = DocumentFormat.OpenXml.Wordprocessing.JustificationValues.Center
                        }
                    };
                    body.Append(titleParagraph);

                    // 添加内容（确保是纯文本）
                    var contentParagraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(
                        new DocumentFormat.OpenXml.Wordprocessing.Run(
                            new DocumentFormat.OpenXml.Wordprocessing.Text(ConvertRtfToPlainText(Content)))
                    );
                    body.Append(contentParagraph);

                    mainPart.Document.Append(body);
                    mainPart.Document.Save();
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"保存 Word 文件失败：{ex.Message}", ex);
            }
        }
        private static string LoadWordContent(string filePath)
        {
            try
            {
                using (var wordDocument = WordprocessingDocument.Open(filePath, false))
                {
                    var body = wordDocument.MainDocumentPart.Document.Body;
                    return body.InnerText; // 获取文档的纯文本内容
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"加载 Word 文件失败：{ex.Message}");
            }
        }
        private void SaveAsPdf(string filePath)
        {
            try
            {
                using (var document = new PdfSharpCore.Pdf.PdfDocument())
                {
                    var page = document.AddPage();
                    var graphics = PdfSharpCore.Drawing.XGraphics.FromPdfPage(page);

                    // 替换字体加载逻辑，使用 PdfSharpCore.Drawing.XFont 直接加载字体
                    var titleFont = new PdfSharpCore.Drawing.XFont("Arial", 16, PdfSharpCore.Drawing.XFontStyle.Bold);
                    var contentFont = new PdfSharpCore.Drawing.XFont("Arial", 12);

                    // 写入标题
                    graphics.DrawString(Title, titleFont, PdfSharpCore.Drawing.XBrushes.Black,
                        new PdfSharpCore.Drawing.XRect(0, 0, page.Width, 50),
                        PdfSharpCore.Drawing.XStringFormats.TopCenter);

                    // 写入内容
                    graphics.DrawString(ConvertRtfToPlainText(Content), contentFont, PdfSharpCore.Drawing.XBrushes.Black,
                        new PdfSharpCore.Drawing.XRect(40, 60, page.Width - 80, page.Height - 100),
                        PdfSharpCore.Drawing.XStringFormats.TopLeft);

                    document.Save(filePath);
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"保存为 PDF 文件失败：{ex.Message}");
            }
        }
        private static string LoadPdfContent(string filePath)
        {
            try
            {
                var text = new StringBuilder();

                // 使用 PdfPig 打开 PDF 文件
                using (var pdfDocument = UglyToad.PdfPig.PdfDocument.Open(filePath))
                {
                    foreach (var page in pdfDocument.GetPages())
                    {
                        // 提取每一页的文本
                        text.AppendLine($"[Page {page.Number}]");
                        text.AppendLine(page.Text);
                        text.AppendLine(); // 添加换行符
                    }
                }

                return text.ToString();
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"加载 PDF 文件失败：{ex.Message}");
            }
        }
        private string ConvertRtfToPlainText(string rtfContent)
        {
            using (var richTextBox = new System.Windows.Forms.RichTextBox())
            {
                try
                {
                    // 检查内容是否是合法的 RTF 格式
                    if (rtfContent.TrimStart().StartsWith(@"{\rtf"))
                    {
                        richTextBox.Rtf = rtfContent; // 加载 RTF 内容
                        return richTextBox.Text; // 返回纯文本内容
                    }
                    else
                    {
                        // 如果不是 RTF 格式，直接返回原始内容
                        return rtfContent;
                    }
                }
                catch (ArgumentException ex)
                {
                    throw new InvalidOperationException($"RTF 转换失败：{ex.Message}");
                }
            }
        }

    }
}
